<template>
  <div class="school">
    <el-card class="box-card">
      <div class="school__time">
        <el-date-picker
          v-model="value1"
          type="datetimerange"
          :disabled="timeDisabled"
          valueFormat="yyyy-MM-dd HH:mm:ss"
          rangeSeparator="至"
          startPlaceholder="填报开始日期"
          endPlaceholder="填报结束日期"/>
        <el-button
          type="primary"
          class="school__time-modify"
          :disabled="disabledButton"
          size="small"
          @click="modifyDate">
          修改
        </el-button>
        <el-button
          type="success"
          class="school__time-upload"
          size="small"
          :disabled="!disabledButton"
          @click="uploadDate">
          保存
        </el-button>
      </div>
    </el-card>

    <el-card class="box-card">
      <div class="school__add">
        <div class="school__add-username addItem">
          <div>用户名：</div>
          <el-input v-model="input1"
                    class="inputItem"
                    placeholder="请输入用户名"
                    clearable/>
        </div>

        <div class="school__add-deptid addItem">
          <div>学校名称：</div>
          <el-select v-model="input2"
                     class="inputItem"
                     filterable
                     placeholder="请选择学校">
            <el-option
              v-for="item in schoolOptions"
              :key="item.id"
              :label="item.schoolName"
              :value="item.id"/>
          </el-select>
        </div>

        <el-button slot="append"
                   type="primary"
                   class="school__add-button"
                   size="small"
                   @click="addUser">
          添加
        </el-button>
      </div>
    </el-card>
    <el-card class="box-card">
      <!-- 搜索 -->
      <div class="select">
        请输入用户名搜索：
        <input v-model="search"
               class="select-input"
               type="text"
               placeholder="请输入用户名">
      </div>

      <el-table
        :border="true"
        stripe
        class="school__table"
        :data="tableData.filter(data => !search || data.user.username.toLowerCase().includes(search.toLowerCase()))"
        style="width: 100%">
        <el-table-column
          label="用户编号"
          width="100"
          prop="user.userid"/>
        <el-table-column
          label="用户名"
          prop="user.username"/>
        <!-- <el-table-column
        label="密码"
        prop="userpassword"/> -->
        <el-table-column
          label="学校编号"
          width="100"
          prop="user.schoolid"/>
        <el-table-column
          label="学校名字"
          prop="schoolName"/>
        <el-table-column
          label="状态"
          width="160"
          prop="user.status">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.user.status"
              activeText="启用"
              inactiveText="禁用"
              activeColor="#13ce66"
              inactiveColor="#ff4949"
              @change="handleDelete(scope.$index,scope.row)"/>
          </template>
        </el-table-column>

        <el-table-column label="操作"
                         width="180">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="success"
                       class="editButton"
                       @click="resetPass(scope.$index, scope.row)">
              重置密码
            </el-button>

            <el-popover v-model="scope.row.visible"
                        placement="top"
                        width="160">
              <p>确定删除吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini"
                           type="text"
                           @click="scope.row.visible = false">
                  取消
                </el-button>
                <el-button type="primary"
                           size="mini"
                           @click="deleteUser(scope.$index, scope.row)">
                  确定
                </el-button>
              </div>
              <el-button slot="reference"
                         size="mini"
                         type="danger">
                删除
              </el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import api from '@/api/systemUser.js'

export default {
  inject: ['reload'],
  created () {
    this.getUser()
    this.getSchool()
    this.getDate()
  },
  mounted () {
    sessionStorage.removeItem('_id')
    sessionStorage.removeItem('show')
  },
  data () {
    return {
      input1: '',
      input2: '',
      start: [],
      end: [],
      value1: [],
      tableData: [],
      search: '',
      disabledText: '禁用',
      schoolOptions: [],
      timeDisabled: true,
      disabledButton: false,
      schoolPage: 1,
      schoolAllPage: 1
    }
  },
  methods: {
    // 获取时间
    async getDate () {
      const res = await api.getDate()
      const { code, result } = res
      if (code == 200 && result) {
        this.value1 = [result.sTime, result.eTime]
      }
    },
    // 修改按钮
    modifyDate () {
      this.timeDisabled = false
      this.disabledButton = true
    },
    // 上传按钮
    async uploadDate () {
      try {
        const sTime = this.value1[0]
        const eTime = this.value1[1]
        const res = await api.uploadDate(sTime, eTime)
        const { code, message } = res
        if (code == 200) {
          this.$message({
            message: '修改成功',
            type: 'success'
          })
          await api.upEndTime(eTime).then(res => {})
          this.disabledButton = false
          this.timeDisabled = true
        } else {
          this.$message({
            message: message,
            type: 'error'
          })
        }
      } catch (err) {
        this.$message({
          message: '修改失败',
          type: 'error'
        })
      }
    },
    // 获取院系字典
    async getSchool () {
      api.getAllSchool(this.schoolPage).then(res => {
        this.schoolOptions.push(...res.result.school)
        this.schoolAllPage = res.result.pages
      })
    },
    // 获取用户信息
    async getUser () {
      this.tableData = []
      const res = await api.getUser()
      const { code, result } = res
      if (code == 200 && result) {
        this.tableData = result.userData
      }
    },
    // 禁用账号
    async changeUser (id) {
      const res = await api.changeUser(id)
      const { code } = res
      if (code == 200) {
        this.open1()
      }
    },
    // 重置密码
    resetPass (index, row) {
      api.putResetPassword(row.user.userid).then(res => {
        const { code } = res
        if (code == 200) {
          this.$notify.success({
            message: `用户 ${row.user.username} 的密码已重置为初始密码（123456）`
          })
        } else {
          this.$notify.success({
            message: '修改失败'
          })
        }
      })
    },
    handleDelete (index, row) {
      this.row = row
      this.changeUser(row.user.userid)
    },
    open1 () {
      if (this.row.user.status == false) {
        this.$message({
          message: '禁用成功，再次点击按钮重新启用！',
          type: 'success'
        })
      } else {
        this.$message({
          message: '启用成功，再次点击按钮重新禁用！',
          type: 'success'
        })
      }
    },
    // 添加用户
    async addUser () {
      if (this.input1 && this.input2) {
        try {
          var params = {}
          params.username = this.input1
          params.schoolid = this.input2
          const res = await api.addUser(params)
          const { code } = res
          if (code == 200) {
            this.getUser()
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.input1 = ''
            this.input2 = ''
          } else {
            this.$message({
              message: '添加失败',
              type: 'error'
            })
          }
        } catch (err) {
          this.$message({
            message: '添加失败',
            type: 'error'
          })
        }
      } else {
        this.$message({
          message: '用户信息不完整，不可添加！',
          type: 'warning'
        })
      }
    },
    async deleteUser (index, row) {
      row.visible = false
      try {
        const res = await api.deleteUser(row.user.userid)
        const { code } = res
        if (code == 200) {
          this.$message({
            message: '删除成功！',
            type: 'success'
          })
          this.getUser()
        } else {
          this.$message({
            message: '删除失败！',
            type: 'error'
          })
        }
      } catch (err) {
        this.$message({
          message: '删除失败！',
          type: 'error'
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.school {
  padding: 30px;
  &__add,
  &__time {
    display: flex;
    justify-content: center;
    align-items: center;
    border: 2px solid #409eff;
    padding: 10px 0;
    &-modify {
      margin-left: 50px;
    }
    &-upload {
      margin-left: 22px;
    }
  }
  .addItem {
    display: flex;
    justify-content: flex-start;
    align-items: center;

  }
  .box-card {
    margin-bottom: 30px;
  }
  .inputItem {
    width: 200px;
  }
  &__srarch {
    width: 50px;
  }
  &__table {
    margin-top: 20px;
  }
  .select {
    font-size: 16px;
    &-input {
      padding-left: 8px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      outline: none;
      width: 250px;
      &:focus {
        border: 1px solid #409eff;
      }
    }
  }
  .selectInput {
    padding-left: 8px;
    border: 1px solid #dcdfe6;
    border-radius: 3px;
    outline: none;
    font-size: 14px;
    width: 188px;
  }
  .selectInput:focus {
    border: 1px solid #409eff;
  }
  .editButton {
    margin-left: 6px;
    margin-right: 10px;
  }
  .prohibitButton {
    margin-left: 30px;
  }
}
</style>
